﻿<html>
<body>

<?php
date_default_timezone_set('Asia/Hong_Kong');  //set time zone
set_error_handler("myHandler");               //set error handler
$chinatime = date('Y-m-d H:i:s');             //get current time
$max_size = 500000;

try
{
	test();
	// logger2(translate("hello"));
	// logger2("");
    // logger2(translate_curl("hello"));
    
}
catch(Exception $e)
{
    logger2("Exception Message: ".$e->getMessage());
}


// GET /openapi.do?keyfrom=doucube&key=1845007487&type=data&doctype=json&version=1.1&q=hi HTTP/1.1
// Host: fanyi.youdao.com
// Connection: keep-alive
// Cache-Control: max-age=0
// User-Agent: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11
// Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
// Accept-Encoding: gzip,deflate,sdch
// Accept-Language: en-US,en;q=0.8
// Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3



function translate_curl($keyword)
{
    $url = "http://fanyi.youdao.com/openapi.do?keyfrom=doucube&key=1845007487&type=data&doctype=json&version=1.1&q=".$keyword;
    //$url = "http://fanyi.youdao.com/openapi.do";
    //$content = file_get_contents("http://fanyi.youdao.com/openapi.do?keyfrom=doucube&key=1845007487&type=data&doctype=json&version=1.1&q=".$keyword);
    //$content = fopen("http://fanyi.youdao.com/openapi.do?keyfrom=doucube&key=1845007487&type=data&doctype=json&version=1.1&q=".$keyword, "r");

    $content = "";
    

    
    
/*     $uri = "http://fanyi.youdao.com/openapi.do"
    //参数数组
    $data = array(
            'keyfrom'         => 'doucube',
            'key'         => '1845007487',
            'type'         => 'data',
            'doctype'         => 'json',
            'version'         => '1.1',
            'q'         => &keyword,
             );
           //操作执行
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $uri);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER,1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_exec($ch); */


    
/*         $fields = array(
            'keyfrom'         => 'doucube',
            'key'         => '1845007487',
            'type'         => 'data',
            'doctype'         => 'json',
            'version'         => '1.1',
            'q'         => &keyword
             ); */
/*     $fields = array(   
                    keyfrom=>doucube ,   
                    key=>1845007487 ,   
                    type=>data,   
                    doctype=>json ,   
                    version=>1.1,   
                    q=>&keyword  
                   ); */

    $url = "http://fanyi.youdao.com/openapi.do?keyfrom=doucube&key=1845007487&type=data&doctype=json&version=1.1&q=".$keyword;
    $ch = curl_init();
    // 2. 设置选项，包括URL
    curl_setopt($ch, CURLOPT_URL, $url);
	// 不想输出返回的内容
	//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // 3. 执行并获取HTML文档内容
    $content = curl_exec($ch);
    // 4. 释放curl句柄
    curl_close($ch);


    //var_dump($content);
    $youdao = json_decode($content, true);
    $errorcode = $youdao['errorCode'];
	$translation = $youdao['translation']['0']; //发音
    // $phonetic = $youdao['basic']['phonetic']; //发音
    // $explains = $youdao['basic']['explains']; //解释
    // //var_dump($explains);
    // $translation = "";
    // foreach ($explains as $value) {
        // $translation = $translation."\r\n".$value;
    // }
    // $result = "";
    // if(isset($errorcode)){
        // switch ($errorcode){
            // case 0:
                // $result = $phonetic."\r\n".$translation;
                // break;
            // case 20:
                // $result = "输入错误：要翻译的文本过长";
                // break;
            // case 30:
                // $result = "系统错误：无法进行有效的翻译";
                // break;
            // case 40:
                // $result = "输入错误：不支持的语言类型";
                // break;
            // case 50:
                // $result = "系统错误：无效的密钥，没有权限翻译";
                // break;
            // default:
                // $result = "系统错误：遇到未知错误，代码：".$errorcode;
                // break;
        // }
    // }
    // else{
        // $result = "没有获得翻译结果？Error Code 为空！";
    // }
	return $youdao['translation']['0'];
    //return $result;
}

function translate($keyword)
{
    $url = "http://fanyi.youdao.com/openapi.do?keyfrom=doucube&key=1845007487&type=data&doctype=json&version=1.1&q=".$keyword;
    //$content = file_get_contents("http://fanyi.youdao.com/openapi.do?keyfrom=doucube&key=1845007487&type=data&doctype=json&version=1.1&q=".$keyword);
    //$content = fopen("http://fanyi.youdao.com/openapi.do?keyfrom=doucube&key=1845007487&type=data&doctype=json&version=1.1&q=".$keyword, "r");

    $content = "";
    $fp = fopen($url, 'r');
    while(!feof($fp)) {
        $content .= fgets($fp, 1024);
    }

    var_dump($content);
    $youdao = json_decode($content, true);
    $errorcode = $youdao['errorCode'];
    $phonetic = $youdao['basic']['phonetic']; //发音
    $explains = $youdao['basic']['explains']; //解释
    $translation = "";
    foreach ($explains as $value) {
        $translation = $translation."\r\n".$value;
    }
    $result = "";
    if(isset($errorcode)){
        switch ($errorcode){
            case 0:
                $result = $phonetic."\r\n".$translation;
                break;
            case 20:
                $result = "输入错误：要翻译的文本过长";
                break;
            case 30:
                $result = "系统错误：无法进行有效的翻译";
                break;
            case 40:
                $result = "输入错误：不支持的语言类型";
                break;
            case 50:
                $result = "系统错误：无效的密钥，没有权限翻译";
                break;
            default:
                $result = "系统错误：遇到未知错误，代码：".$errorcode;
                break;
        }
    }
    else{
        $result = "没有获得翻译结果？Error Code 为空！";
    }
    return $result;
}

function test()
{
	$url = "http://fanyi.youdao.com/openapi.do?keyfrom=doucube&key=1845007487&type=data&doctype=json&version=1.1&q=".urlencode("test");
	
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$output = curl_exec($ch);
	
	if(curl_errno($ch))
	{ echo 'CURL ERROR Code: '.curl_errno($ch).', reason: '.curl_error($ch);}
	
	curl_close($ch);

    var_dump($output);
    $youdao = json_decode($output, true);
    $errorcode = $youdao['errorCode'];
    $phonetic = $youdao['basic']['phonetic']; //发音
    $explains = $youdao['basic']['explains']; //解释
    $translation = "";
    foreach ($explains as $value) {
        $translation = $translation.$value."\n";
    }
    $result = "";
    if(isset($errorcode)){
        switch ($errorcode){
            case 0:
                $result = $phonetic."\n".$translation;
				$result = $translation;
                break;
            case 20:
                $result = "输入错误：要翻译的文本过长";
                break;
            case 30:
                $result = "系统错误：无法进行有效的翻译";
                break;
            case 40:
                $result = "输入错误：不支持的语言类型";
                break;
            case 50:
                $result = "系统错误：无效的密钥，没有权限翻译";
                break;
            default:
                $result = "系统错误：遇到未知错误，代码：".$errorcode;
                break;
        }
    }
    else{
        $result = "没有获得翻译结果？请与作者联系！";
    }
	//return $youdao['translation']['0'];
    return $result;
}

//record operation log into .log file
function logger($log_content)
{
    print_r(date('H:i:s')." ".$log_content."<br />");
    $log_filename = date("Ymd").".log";
    $file = fopen($log_filename ,"a+");
    fwrite($file, date('H:i:s')." ".$log_content."\r\n");
    fclose($file);
}
//record operation log into .log file
function logger2($log_content)
{
    Global $max_size;
    print_r(date('H:i:s')." ".$log_content." "."<br />");
    $log_filename = date("Ymd").".log";
    if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);sleep(1);}
    file_put_contents($log_filename, date('H:i:s')." ".$log_content."\r\n", FILE_APPEND);
}
//error handler function
function myHandler($level, $message, $file, $line, $context)
{
    logger("<b>[ERROR]</b> LEVEL: $level, MESSAGE: $message, FILE: $file, LINE: $line, CONTENT: $context");
    die();
}


?>

</body>
</html>